﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using EPiServer.Editor;
using EPiServer.Web;
using EPiServer.Web.PropertyControls;

namespace OpenWaves.EPiServer.GeoProperties
{
    public abstract class PropertyGeoObjectControl<T>: PropertyDataControl, IRenderTemplate<T>
    {
        public override void CreateDefaultControls()
        {
            var imageContainer = new GeoObjectPropertyWebControl(HtmlTextWriterTag.Div);

            const string geoWrapperClass = "geo-wrapper";

            if (PageEditing.PageIsInEditMode)
            {
                var literalControl = new LiteralControl
                    {
                        Text =
                            string.Concat("<style type=\"text/css\" rel=\"stylesheet\">.", geoWrapperClass, " { display:inline-block; }</style>")
                    };
                this.Page.Header.Controls.Add(literalControl);
            }

            this.CopyWebAttributes(imageContainer);

            if (string.IsNullOrEmpty(imageContainer.CssClass))
            {
                imageContainer.CssClass = geoWrapperClass;
            }
            else
            {
                imageContainer.CssClass += geoWrapperClass;
            }

            var mapUrl = this.CreateMapUrl((T)this.PropertyData.Value);

            if (!String.IsNullOrEmpty(mapUrl))
            {
                var image = new Image {ImageUrl = mapUrl};
                image.Attributes["onerror"] = "this.onerror=null; console.log('Please check your web.config file looking for valid Google Maps Api Key settings.')";
                imageContainer.Controls.Add(image);                
            }                                        

            this.Controls.Add(imageContainer);
        }

        protected abstract string CreateMapUrl(T value);    
    }

    class GeoObjectPropertyWebControl : WebControl
    {
        public GeoObjectPropertyWebControl(HtmlTextWriterTag tag)
            : base(tag)
        {
        }
    }
}